package com.caipiao.service.impl;

import com.caipiao.mapper.*;
import com.caipiao.pojo.*;
import com.caipiao.service.PlanService;
import com.caipiao.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.*;

/**
 * Created by Administrator on 2019/1/7.
 */
@Service
@Transactional
public class PlanServiceImpl implements PlanService {

    private static final Logger LOG = LoggerFactory.getLogger(IndexServiceImpl.class);

    @Autowired
    private SPlanMapper sPlanMapper;
    @Autowired
    private SPlanItemMapper sPlanItemMapper;
    @Autowired
    private SMemberMapper sMemberMapper;
    @Autowired
    private SUserMemberMapper sUserMemberMapper;
    @Autowired
    private SUserPlanMapper sUserPlanMapper;
    @Autowired
    private SUserMapper sUserMapper;
    @Autowired
    private SIntegralMapper sIntegralMapper;
    @Autowired
    private SPlanToPlanItemBMapper sPlanToPlanItemBMapper;
    @Autowired
    private SPlanWithMapper sPlanWithMapper;


    @Override
    public ObjectResult index(XMLBean xmlBean) {
        List<SPlanItem> planItems = sPlanItemMapper.selectplanItem(xmlBean.getMatchState());

        Page<SPlanItem> page = new Page<>();
        page.setP(xmlBean.getP() == null? 1:xmlBean.getP());
        List<SPlanItem> pageContent = page.getPageContent(planItems);

        List<Map<String,Object>> list = new ArrayList<>();

        for (SPlanItem sPlanItem:pageContent){
            if (new Date().compareTo(sPlanItem.getStartTime())>0&&sPlanItem.getStatus()!=2) sPlanItem.setStatus(1);

            String day = DateUtil.formatDate(sPlanItem.getStartTime());
            Boolean flag = false;

            for (Map<String,Object> map:list){
                String str = (String) map.get("day");
                if (day.equals(str)){
                    flag = true;
                    List<SPlanItem> list1 = (List<SPlanItem>)map.get("list");
                    list1.add(sPlanItem);
                    break;
                };
            }

            if (!flag){
                Map<String,Object> map = new HashMap<>();
                map.put("day",day);
                List<SPlanItem> list2 = new ArrayList<>();
                list2.add(sPlanItem);
                map.put("list",list2);
                list.add(map);
            }
            //方案数
            sPlanItem.setPlanCount(sPlanMapper.selectplanCountByPlanItemId(sPlanItem.getId()));
            sPlanItem.setLogo1(ConfigUtils.ADMIN_URL+sPlanItem.getLogo1());
            sPlanItem.setLogo2(ConfigUtils.ADMIN_URL+sPlanItem.getLogo2());
        }

        Map<String,Object> map = new HashMap<>();
        map.put("count",page.getPageTotal());
        map.put("list",list);

        return ObjectResult.build("1","成功",map);
    }

    @Override
    public ObjectResult matchDetails(XMLBean xmlBean) {
        SPlanItem sPlanItem = sPlanItemMapper.selectplanItemById(Integer.parseInt(xmlBean.getId()));

        sPlanItem.setLogo1(ConfigUtils.ADMIN_URL+sPlanItem.getLogo1());
        sPlanItem.setLogo2(ConfigUtils.ADMIN_URL+sPlanItem.getLogo2());
        Integer planCount = sPlanMapper.selectplanCountByPlanItemId(sPlanItem.getId());
        sPlanItem.setPlanCount(planCount == null ? 0:planCount);

        List<SPlan> list = sPlanMapper.selectplantByPlanItemId(Integer.parseInt(xmlBean.getId()));

        Page<SPlan> page = new Page<>();
        page.setP(xmlBean.getP()==null? 0:xmlBean.getP());
        List<SPlan> pageContent = page.getPageContent(list);

        for (SPlan sPlan:pageContent){
            sPlan.setTime(RelativeDateFormat.data(sPlan.getAddTime()));
        }

        Map<String,Object> map = new HashMap<>();
        map.put("list",pageContent);
        map.put("planItem",sPlanItem);
        map.put("count",page.getPageTotal());

        return ObjectResult.build("1","成功",map);
    }

    @Override
    public ObjectResult  planDetails(XMLBean xmlBean) {
        //方案详情
        SPlan sPlan = sPlanMapper.selectByPrimaryKey(Integer.parseInt(xmlBean.getId()));
        if (sPlan==null){
            return ObjectResult.build("0","找不到方案");
        }

        if(StringUtil.isEmpty(sPlan.getInfo())){
            sPlan.setInfo("无");
        }

        //单关
        if(sPlan.getPlanType()==1) {
            LinkedList<SPlanItem> sPlanItems = sPlanItemMapper.selectplanItemByPlanId(Integer.parseInt(xmlBean.getId()));
            if(sPlanItems.size()>0) {
                for (SPlanItem sPlanItem : sPlanItems) {
                    if (sPlanItem.getStartTime().compareTo(new Date()) > 0) {
                        sPlanItems.remove(sPlanItem);
                        continue;
                    }
                    sPlanItem.setLogo1(ConfigUtils.ADMIN_URL + sPlanItem.getLogo1());
                    sPlanItem.setLogo2(ConfigUtils.ADMIN_URL + sPlanItem.getLogo2());
                    if(StringUtil.isEmpty(sPlanItem.getBuyRate())){
                        String[] split = {};
                        sPlanItem.setBuyRateArray(split);
                    }else {
                        String[] split = sPlanItem.getBuyRate().split(",");
                        sPlanItem.setBuyRateArray(split);//专家预测
                    }
                }
            }
            sPlan.setList(sPlanItems);
        }
        //二串一
        if(sPlan.getPlanType()==2) {
            LinkedList<SPlanToPlanItemB> sPlanToPlanItemBS = sPlanToPlanItemBMapper.select(xmlBean.getId());
            if (sPlanToPlanItemBS != null && sPlanToPlanItemBS.size()>0) {
                for (SPlanToPlanItemB sPlanToPlanItemB : sPlanToPlanItemBS) {
                    if (sPlanToPlanItemB.getStart_timeb().compareTo(new Date()) > 0) {
                        sPlanToPlanItemBS.remove(sPlanToPlanItemB);
                        continue;
                    }
                    sPlanToPlanItemB.setLogo1(ConfigUtils.ADMIN_URL + sPlanToPlanItemB.getLogo1());
                    sPlanToPlanItemB.setLogo2(ConfigUtils.ADMIN_URL + sPlanToPlanItemB.getLogo2());
                    sPlanToPlanItemB.setLogo3(ConfigUtils.ADMIN_URL + sPlanToPlanItemB.getLogo3());
                    sPlanToPlanItemB.setLogo4(ConfigUtils.ADMIN_URL + sPlanToPlanItemB.getLogo4());

                    if(StringUtil.isEmpty(sPlanToPlanItemB.getBuyRate())){
                        String[] split = {};
                        sPlanToPlanItemB.setBuyRateArray(split);//专家预测
                    }else {
                        String[] split = sPlanToPlanItemB.getBuyRate().split(",");
                        sPlanToPlanItemB.setBuyRateArray(split);//专家预测
                    }

                    if(StringUtil.isEmpty(sPlanToPlanItemB.getBuyRateB())){
                        String[] split2 ={};
                        sPlanToPlanItemB.setBuyRateBArray(split2);//专家预测2
                    }else {
                        String[] split2 = sPlanToPlanItemB.getBuyRateB().split(",");
                        sPlanToPlanItemB.setBuyRateBArray(split2);//专家预测2
                    }
                }
            }
            sPlan.setList(sPlanToPlanItemBS);
        }
        //总进球
        if(sPlan.getPlanType()==3){
            LinkedList<SPlanItem> sPlanItems = sPlanItemMapper.selectplanItemCByPlanId(xmlBean.getId());
            if(sPlanItems != null && sPlanItems.size()>0){
                for (SPlanItem sPlanItem:sPlanItems){
                    if(sPlanItem.getStartTime().compareTo(new Date())>0){
                        sPlanItems.remove(sPlanItem);
                        continue;
                    }
                    sPlanItem.setLogo1(ConfigUtils.ADMIN_URL+sPlanItem.getLogo1());
                    sPlanItem.setLogo2(ConfigUtils.ADMIN_URL+sPlanItem.getLogo2());
                    if(StringUtil.isEmpty(sPlanItem.getDisplayRate())){
                        String[] split = {};
                        sPlanItem.setRateArray(split);
                    }else {
                        String[] split = sPlanItem.getDisplayRate().split(",");//赔率数组
                        sPlanItem.setRateArray(split);
                    }

                    if(StringUtil.isEmpty(sPlanItem.getBuyRate())){
                        String[] split = {};
                        sPlanItem.setBuyRateArray(split);
                    }else {
                        String[] split = sPlanItem.getBuyRate().split(",");
                        sPlanItem.setBuyRateArray(split);//专家预测
                    }

                }
            }
            sPlan.setList(sPlanItems);
        }


        sPlan.setTime(RelativeDateFormat.data(sPlan.getAddTime()));
//        sPlan.setStartTime(DateUtil.addDateHour(sPlan.getStartTime(),-1));
        sPlan.setRecommend(sPlan.getInfo());
//        sUserPlanMapper.selectByPrimaryKey(sPlan.getId()).getIsWin(

//        sPlan.setIsWin(sUserPlanMapper.selectByPrimaryKey(sPlan.getId()).getIsWin());

        Map<String,Object> map = new HashMap<>();
        map.put("memberId",sPlan.getMemberId());
        map.put("matchState","(1)");
        map.put("id",xmlBean.getId());
        //专家其他方案
        List<SPlan> plans = sPlanMapper.selectplantByMemberId(map);

        for (SPlan sPlan1:plans){
            sPlan1.setTime(RelativeDateFormat.data(sPlan1.getAddTime()));
        }
        //专家信息
        SMember sMember = sMemberMapper.selectByPrimaryKey(sPlan.getMemberId());
        sMember.setHead(ConfigUtils.ADMIN_URL+sMember.getHead());

        //是否关注
        if(!StringUtil.isEmpty(xmlBean.getToken())){
            String userId = CommonUtils.decToken(xmlBean.getToken());
            SUserMember member = new SUserMember();
            member.setUserId(Integer.parseInt(userId));
            member.setMemberId(sPlan.getMemberId());
            Integer isFollow = sUserMemberMapper.select(member);
            if (isFollow == null){
                sMember.setIsFollow(0);
            }else {
                sMember.setIsFollow(isFollow);
            }
        }else {
            sMember.setIsFollow(0);
        }


        map.clear();
        map.put("plan",sPlan);
        map.put("plans",plans);
        map.put("member",sMember);
        if(sPlan.getStartTime().compareTo(new Date())<0||sPlan.getMatchState()!=1){
            map.put("isPay",0);
        }else {
            map.put("isPay",1);
        }

        return ObjectResult.build("1","成功",map);

    }

    @Override
    public ObjectResult planBuy(XMLBean xmlBean) {
        String userId = CommonUtils.decToken(xmlBean.getToken());

        int hour = Integer.parseInt(DateUtil.formatDateHH());

//        if(hour <9 || hour >= 22){
//            return ObjectResult.build("0","可购买时间为9:00-22:00");
//        }

        SUser sUser = sUserMapper.selectByPrimaryKey(Integer.parseInt(userId));
        SPlan sPlan = sPlanMapper.selectByPrimaryKey(Integer.parseInt(xmlBean.getId()));

        Float money = sPlan.getMoney()*xmlBean.getPayCount();
        if (sPlan == null){
            return ObjectResult.build("0","找不的方案");
        }
        if(sUser.getAccountAble()<money){
            return ObjectResult.build("0","积分不足，请联系客服");
        }
        if(DateUtil.getOffsetMinutes(sPlan.getStartTime(),new Date())>60){
            return ObjectResult.build("0","该方案已停止售卖");
        }

        try {
            //添加购买记录
            SUserPlan sUserPlan = new SUserPlan();
            sUserPlan.setPlanId(sPlan.getId());
            sUserPlan.setUserId(sUser.getId());

//            SUserPlan select = sUserPlanMapper.select(sUserPlan);
//            if(select !=null){
//                return ObjectResult.build("0","您已购买该方案");
//            }

            sUserPlan.setAddTime(new Date());
            sUserPlan.setModifyTime(new Date());
            sUserPlan.setStatus(1);
            sUserPlan.setBuy(money);
            sUserPlan.setIsWin(0);
            sUserPlan.setPayCount(xmlBean.getPayCount());
            sUserPlan.setRest(money);
            sUserPlanMapper.insertSelective(sUserPlan);

            //修改用户积分
            sUser.setAccountAble(sUser.getAccountAble()-money);
            sUser.setFrozen(sUser.getFrozen()+money);
            sUserMapper.updateByPrimaryKeySelective(sUser);

            //积分记录
            Map<String,Object> map = new HashMap<>();
            map.put("userId",Integer.parseInt(userId));
            map.put("integral",0-money);
            map.put("type",2);
            map.put("planId",xmlBean.getId());
            sIntegralMapper.insertIntegralByMap(map);

        }catch (RuntimeException e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            ExceptionUtil.logError(e,LOG);
            return ObjectResult.build("0","购买失败");
        }
        return ObjectResult.build("1","购买成功");

    }

    @Override
    public void jpush() {
        List<SPlanItem> sPlanItems = sPlanItemMapper.selectplanItemSoon();
        if(sPlanItems.size()>0){
            for (SPlanItem sPlanItem:sPlanItems){
                String content = sPlanItem.getTitle1()+" VS "+sPlanItem.getTitle2()+" "
                        +DateUtil.formatTimeForHour(sPlanItem.getStartTime())+"比赛即将开始，敬请关注。";
                JpushUtil.sendPush(content);
            }
        }
    }

    @Override
    public ObjectResult planWith(XMLBean xmlBean) {
        String userId = CommonUtils.decToken(xmlBean.getToken());
        float value = Float.parseFloat(xmlBean.getValue());
        SUser sUser = sUserMapper.selectByPrimaryKey(Integer.parseInt(userId));
        if(sUser.getAccountAble()<value){
            return ObjectResult.build("0","可用积分不足");
        }

        Map<String,Object> map = new HashMap<>();
        map.put("userId",userId);
        map.put("status",0);
        List<SPlanWith> sPlanWiths = sPlanWithMapper.selectByUserId(map);

        try {
            if (sPlanWiths.size() == 0) {
                SPlanWith sPlanWith = new SPlanWith();
                sPlanWith = new SPlanWith();
                sPlanWith.setUserId(Integer.parseInt(userId));
                sPlanWith.setMemberId(Integer.parseInt(xmlBean.getId()));
                sPlanWith.setType(Integer.parseInt(xmlBean.getType()));
                sPlanWith.setValue(value);
                sPlanWith.setSurplusValue(value);
//                sPlanWith.setPayCount(xmlBean.getPayCount());
                sPlanWith.setCount(xmlBean.getCount());
                sPlanWith.setAddTime(new Date());
                sPlanWithMapper.insertSelective(sPlanWith);
            } else {
                return ObjectResult.build("0", "计划连续跟投已在进行中");
            }
//            else {//有则修改
//                sPlanWith.setMemberId(Integer.parseInt(xmlBean.getId()));
//                sPlanWith.setType(Integer.parseInt(xmlBean.getType()));
//                sPlanWith.setValue(Float.parseFloat(xmlBean.getValue()));
//                sPlanWith.setSurplusValue(value);
////                sPlanWith.setPayCount(xmlBean.getPayCount());
//                sPlanWith.setCount(xmlBean.getCount());
//                sPlanWith.setAddTime(new Date());
//                sPlanWithMapper.updateByPrimaryKeySelective(sPlanWith);
//            }
            //修改用户积分
            sUser.setAccountAble(sUser.getAccountAble()-value);
            sUser.setFrozen(sUser.getFrozen()+value);
            sUserMapper.updateByPrimaryKeySelective(sUser);

            return ObjectResult.build("1", "连续跟投成功");
        }catch (RuntimeException e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            ExceptionUtil.logError(e,LOG);
            return ObjectResult.build("0","连续跟投失败");
        }
    }

    @Override
    public ObjectResult selectPlanWith(XMLBean xmlBean) {
        String userId = CommonUtils.decToken(xmlBean.getToken());
        Map<String,Object> map = new HashMap<>();
        map.put("userId",userId);
        List<SPlanWith> sPlanWiths = sPlanWithMapper.selectByUserId(map);
        Page<SPlanWith> page = new Page<>();
        page.setP(xmlBean.getP()==null? 1:xmlBean.getP());
        page.setPageSize(10);
        List<SPlanWith> pageContent = page.getPageContent(sPlanWiths);
        for (SPlanWith sPlanWith:pageContent) {
            switch (sPlanWith.getType()){
                case 1:sPlanWith.setTitle("专家");break;
                case 2:sPlanWith.setTitle("单关");break;
                case 3:sPlanWith.setTitle("二串一");break;
                case 4:sPlanWith.setTitle("总进球");break;
                default:break;
            }
        }

        map.clear();
        map.put("list",pageContent);
        map.put("count",page.getPageTotal());
        return ObjectResult.build("1","成功",map);
    }

    @Override
    public ObjectResult cancelPlanWith(XMLBean xmlBean) {
        String userId = CommonUtils.decToken(xmlBean.getToken());

        SPlanWith sPlanWith = sPlanWithMapper.selectByPrimaryKey(Integer.parseInt(xmlBean.getId()));
        if(sPlanWith==null){
            return ObjectResult.build("0","不存在的跟单记录");
        }
        if (sPlanWith.getUserId()!=Integer.parseInt(userId)){
            return ObjectResult.build("0","错误的跟单人");
        }
        if (sPlanWith.getStatus()==1){
            return ObjectResult.build("0","此跟单已结束");
        }
        //修改为已结束状态
        sPlanWith.setStatus(1);
        sPlanWith.setSurplusValue(0f);
        sPlanWithMapper.updateByPrimaryKeySelective(sPlanWith);

        //返回未使用的积分
        if(sPlanWith.getSurplusValue()>0) {
            SUser sUser = sUserMapper.selectByPrimaryKey(Integer.parseInt(userId));
            sUser.setAccountAble(sUser.getAccountAble()+sPlanWith.getSurplusValue());
            sUser.setFrozen(sUser.getFrozen()+sPlanWith.getSurplusValue());
            sUserMapper.updateByPrimaryKeySelective(sUser);
        }
        return ObjectResult.build("1","连续跟单取消成功");
    }
}
